<script setup lang="ts">
import {onMounted, onUnmounted, reactive, ref, toRef, watch} from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import moment from 'moment/moment'
import { useDeviceListApi } from '@/api/gps/device'
import { VideoCameraFilled, Timer, Folder, Download } from '@element-plus/icons-vue'
import { queryHistory2, uploadRequest, UploadAv, uploadControl } from '@/api/gps/jt808/jt1078'
import { jt1078AvsetAnalysis, bytesToSize, formatDuration, timeFormat } from '@/utils/gps/format'
import { storeToRefs } from 'pinia'

import { nanoid } from 'nanoid'
import { usePlaybackStore } from '@/store/gps/playback'
import { recordSelect } from '@/utils/tool'
import {gpsbus, playbackBus} from '@/utils/gps/event'
import { getNodeTypeIcon } from '@/utils/gps/device'
const playbackStore = usePlaybackStore()
const { playbackList, curPlayBackDeviceImei, curPlayingIndex, newPlayingIndex, curRecordData } = storeToRefs(playbackStore)

// const emits = defineEmits(['requestDownload'])
const ruleFormRef = ref<FormInstance>()
const searchLoading = ref(false)
const searchDeviceList = ref<any[]>([])
const loading = ref(false)

const recordList = ref<any[]>([])
const channelList = ref<{ imei: string; channel: number; name: string }[]>([])
const playingRecord = ref()
const playbackRecordRef = ref()

const ruleForm = reactive({
  imei: '',
  channel: undefined as undefined | number,
  startTime: `${moment().format('YYYY-MM-DD')} 00:00:00`,
  endTime: `${moment().format('YYYY-MM-DD')} 23:59:59`,
  streamType: 2,
  storageType: 1,
  mediaType: 0
})

watch(newPlayingIndex, (val) => {
  recordHandle({ target: playbackRecordRef.value.children[val] }, recordList.value[val])
})

onMounted(()=>{
  gpsbus.on("playbackInit", initData)
})
onUnmounted(()=>{
  gpsbus.off('playbackInit')
})

function initData(imei: string) {
  // console.log(imei)
  ruleForm.imei = imei
  remoteSearchMethod(imei)
  setTimeout(() => {
    deviceChange(imei)
  }, 500)
}

// /**
//  * 获取设备列表
//  */
// function getDeviceList() {
//   useDeviceListApi({
//     pageNum: 1,
//     pageSize: 1000
//   }).then((res) => {
//     searchDeviceList.value = res.data.list
//   })
// }
/**
 * 远程搜索
 */
function remoteSearchMethod(val: string) {
  if (val && val.length >= 1) {
    searchLoading.value = true
    const queryForm1 = {
      deptId: null,
      connectionStatus: 'online',
      onlyVideo: true,
      keyWords: val,
      orderField: 'signal_update_time',
      order: 'DESC',
      pageNum: 1,
      pageSize: 1000
    }
    useDeviceListApi(queryForm1)
      .then((res) => {
        searchDeviceList.value = res.data.list
      })
      .finally(() => (searchLoading.value = false))
  } else {
    searchDeviceList.value = []
  }
}

async function query() {
  loading.value = true
  try {
    playbackBus.emit('queryPlaybackTrack', [ruleForm.startTime, ruleForm.endTime])
    const { data } = await queryHistory2(ruleForm)
    const total = data?.history?.count
    recordList.value = data?.history?.items
      .map((item, i) => {
        const s = moment(item.startTime, 'YYMMDDHHmmss')
        const e = moment(item.endTime, 'YYMMDDHHmmss')
        const ss = e.diff(s, 'seconds')
        return {
          ...item,
          startTimeMoment: s,
          endTimeMoment: e,
          diff: formatDuration(ss),
          index: total - i
          // .format('mm分ss秒')
        }
      })
      ?.sort((a, b) => a['startTime'] - b['startTime'])
    playbackList.value = recordList.value
  } catch (error) {
  } finally {
    loading.value = false
  }
}

/**
 * 选中设备的回调事件，初始化通道列表
 * @param val
 */
function deviceChange(val: string) {
  playbackStore.reset()
  curPlayBackDeviceImei.value = val
  recordList.value = []
  channelList.value.splice(0)
  const { jt1078Avch, jt1078Avset, imei } = searchDeviceList.value.find((item) => item.imei === val)
  const channelNames = jt1078AvsetAnalysis(jt1078Avch, jt1078Avset)
  channelList.value.push({ imei, channel: 0, name: '全部通道' })
  if (channelNames.length > 0) {
    for (let i = 0; i < channelNames.length; i++) {
      let cl = channelNames[i]
      channelList.value.push({ imei, channel: cl.channel, name: cl.name })
    }
  }
  if (channelList.value.length > 0) {
    ruleForm.channel = channelList.value[1].channel
  } else {
    ruleForm.channel = 0
  }
}

/**
 * 播放记录被选中的回调事件
 * @param event
 * @param data
 * initVideo: PlayBackControl组件内部方法 用于创建一个新的视频链接
          @play-record="rightRef?.initVideo"
 */
function recordHandle(event, data) {
  curPlayingIndex.value = recordSelect(event, playingRecord)
  curRecordData.value = data
  playbackBus.emit('playbackRecordSelection')
  // uploadRequest({
  //   imei: ruleForm.imei,
  //   channel,
  //   startTime: startTimeMoment.format('YYYY-MM-DD HH:mm:ss'),
  //   endTime: endTimeMoment.format('YYYY-MM-DD HH:mm:ss'),
  //   mediaType,
  //   storageType,
  //   streamType,
  //   condition: 0b0111
  // } as UploadAv).then((d) => {
  //   console.log(d)
  // })
  // uploadControl(ruleForm.imei, 85, 1).then((d) => {
  //   console.log(d)
  // })
}

/**
 * 下载事件
 * @param event
 * @param data
 */
function downloadEvent(event, data) {
  ElMessage.info('正在请求下载，请稍等')
  const { mediaType, storageType, streamType, startTimeMoment, endTimeMoment, channel } = data
  const req = {
    imei: curPlayBackDeviceImei.value,
    channel,
    startTime: startTimeMoment.format('YYYY-MM-DD HH:mm:ss'),
    endTime: endTimeMoment.format('YYYY-MM-DD HH:mm:ss'),
    mediaType,
    storageType,
    streamType,
    condition: 0b0111
  } as UploadAv
  uploadRequest(req).then((res) => {
    // const { respNo } = res.data
    // uploadControl(data.imei, respNo, 1).then(res =>{
    //
    // })
  })
}

defineExpose({
  initData
})
</script>

<template>
  <div class="content">
    <div class="control">
      <el-form ref="ruleFormRef" :model="ruleForm" label-width="70" label-position="left">
        <el-form-item label="设备" prop="imei">
          <el-select
            v-model="ruleForm.imei"
            placeholder="搜索"
            filterable
            clearable
            remote
            :remote-method="remoteSearchMethod"
            :loading="searchLoading"
            @change="deviceChange">
            <el-option v-for="item in searchDeviceList" :key="item.imei" :label="item.plateNo" :value="item.imei">
              <i class="zTree_icon" :style="getNodeTypeIcon(item.connectionStatus, item.type)"></i>
              <span>{{ item.plateNo }}</span>
              <span style="margin-left: 15px">{{ item.imei }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通道" prop="channel">
          <el-select v-model="ruleForm.channel" :disabled="!ruleForm.imei">
            <el-option v-for="item in channelList" :key="item.channel" :label="item.name" :value="item.channel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="ruleForm.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="ruleForm.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" />
        </el-form-item>
        <el-form-item label="码流类型" prop="streamTypeActOp">
          <el-radio-group v-model="ruleForm.streamType" class="margin-r">
            <el-radio :value="0" border>全部</el-radio>
            <el-radio :value="1" border>主码</el-radio>
            <el-radio :value="2" border>子码</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="码流类型" prop="storageTypeOp">
          <el-radio-group v-model="ruleForm.storageType" class="margin-r">
            <el-radio :value="0" border>全部</el-radio>
            <el-radio :value="1" border>主存</el-radio>
            <el-radio :value="2" border>灾备</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="码流类型" prop="mediaTypeOp">
          <el-radio-group v-model="ruleForm.mediaType" class="margin-r">
            <el-radio :value="0" border>全部</el-radio>
            <el-radio :value="1" border>音频</el-radio>
            <el-radio :value="2" border>视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" round style="width: 100px" @click="query">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider style="margin: 10px 0" />
    <div v-loading="loading" class="list">
      <div>
        <span>历史记录</span>
        <span style="float: right">共有{{ recordList.length }}记录</span>
      </div>
      <el-scrollbar class="scrollbar_height">
        <ul ref="playbackRecordRef">
          <li v-for="(item, i) in recordList" :key="i" class="record" :data-key="nanoid()" :data-index="i" @click="(e) => recordHandle(e, item)">
            <span class="record_item prohibit">
              <el-icon size="16" color="rgb(64, 158, 255)" class="transform_y"><VideoCameraFilled /></el-icon>
              {{ item.index }}
            </span>
            <div class="flex_column prohibit">
              <span class="record_item">
                {{ `${item.startTimeMoment.format('HH:mm:ss')} - ${item.endTimeMoment.format('HH:mm:ss')}` }}
              </span>
              <div class="flex_row">
                <span class="record_item">
                  <el-icon size="16" color="red" class="transform_y"><Timer /></el-icon>
                  {{ item.diff }}
                </span>
                <span class="record_item">
                  <el-icon size="16"><Folder /></el-icon>
                  {{ `${bytesToSize(item.size)}` }}
                </span>
              </div>
            </div>
            <span class="record_item" @click.stop="(e) => downloadEvent(e, item)">
              <el-icon size="16" color="rgb(64, 158, 255)"><Download /></el-icon>
            </span>
          </li>
        </ul>
      </el-scrollbar>
    </div>
  </div>
</template>

<style scoped lang="scss">
.content {
  height: calc(100% - 54px);
}
.margin-r > label {
  margin-right: 10px;
}
.list {
  height: calc(100% - 412px);
}
.scrollbar_height {
  height: calc(100% - 19px);
}
ul {
  margin: 0;
}
li {
  list-style: none;
}
li:nth-child(even) {
  background-color: rgb(250, 250, 250);
}
.record {
  padding: 10px 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}
.record_item:not(:nth-child(1)) > i {
  transform: translateY(2px);
}
.record:hover {
  background-color: rgba(160, 207, 255, 0.5);
}
.prohibit {
  pointer-events: none;
}
.on {
  background-color: #ffa0a0 !important;
}
.flex_column {
  display: flex;
  flex-direction: column;
  width: 220px;
}
.flex_row {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.transform_y {
  transform: translateY(2px);
}
.zTree_icon {
  margin-right: 2px;
  vertical-align: center;
  line-height: 0;
  width: 16px;
  height: 16px;
  display: inline-block;
  border: 0 none;
  cursor: pointer;
  outline: none;
  transform: translateY(2px);
}
</style>
